<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有!                                |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: angl<anguolei@clcw.com.cn>                                     |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Broker;
use Think\Log;


/**
 * 红包类
 * Class Broker
 * @author angl
 */
class Commission
{
    private $aid = null;

    public function __construct($aid)
    {
        $this->aid = $aid;
    }

    /**
     * 新增红包记录 ,更新经纪人累积金额,每日红包金额,团队累积金额,团队每日金额
     * @param $rp_id
     * @param $aid
     * @param $other_aid
     * @param $type
     * @param $amount
     * @param int $type
     * @param int $car_id
     * @return bool|mixed
     */
    public static function addLog($rp_id, $aid, $other_aid, $type, $amount, $car_id = 0)
    {
        if (intval($rp_id) < 1 || intval($aid) < 1 || $type < 1 || empty($amount)) {
            return false;
        }
        $agent_info = Broker::getDetailByAid($aid);
        if (empty($agent_info)) {
            return false;
        }
        $data = [
            'rp_id' => $rp_id,
            'aid' => $aid,
            'other_aid' => $other_aid,
            'commission_type' => $type,
            'amount' => $amount,
            'car_id'=> $car_id,
            'type' => 1,
            'create_time' => date("Y-m-d H:i:s")
        ];

        M()->startTrans();
        $ret = M('commission_log')->add($data);
        //经纪人钱包
        $Agent = M("agent");
        $ret1 = $Agent->where("aid=$aid")->setInc('total_money',$amount);
        $ret2 = $Agent->where("aid=$aid")->setInc('wallet',$amount);
        //发展红包
        if($type==1 || $type==4){
            $ret3 = $Agent->where("aid=$aid")->setInc('develop_deal',$amount);
        }
        //直接红包
        if($type==2){
            $ret3 = $Agent->where("aid=$aid")->setInc('direct_deal',$amount);
        }
        //间接红包
        if($type==3){
            $ret3 = $Agent->where("aid=$aid")->setInc('direct_deal',$amount);
        }
        
        if(!$ret){
            Log::record("commission_log插入失败","ERR",true);
            M()->rollback();
            return false;
        }

        if(!$ret1 || !$ret2 || !$ret3){
            Log::record("更新经纪人信息失败","ERR",true);
            M()->rollback();
            return false;
        }

        M()->commit();
        return true;
    }
    
    /**
     * 红包管理列表
     */
    public static function get_commission_list($page, $page_size, $params){
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = array();
        /**
         * 搜索条件：1、红包ID 2、红包类型 3、经纪人UID 4、经纪人帐号 5、车辆ID 6、开始时间 7、结束时间
         */
        if($params['c_id']){
            $map['cl.id'] = array('LIKE','%' . $params['c_id'] . '%');
        }
        if($params['c_type']){
            $map['cl.commission_type'] = array('eq',$params['c_type'],array('neq','5'));
        }else{
            $map['cl.commission_type'] = array('neq','5');
        }
        if($params['agent_uid']){
            $map['a.uid'] = array('eq',$params['agent_uid']);
        }
        if($params['agent_phone']){
            $agent_phone = trim($params['agent_phone']);
            $user = new \AuctionCore\Account\FrontUser();
            $info = $user->get_user_info_by_pwd_mobile($agent_phone);
            $agent = \AuctionCore\Broker\Broker::get_detail_by_uid($info['uid']);
            $map['cl.aid'] = array('eq',$agent['aid']);
        }
        if($params['car_no']){
            $map['c.car_no'] = array('eq',$params['car_no']);
        }
        if($params['start_time']){
            $map['cl.create_time'] = array('egt',$params['start_time'] . ' 00:00:00');
        }
        if($params['end_time']){
            $map['cl.create_time'] = array('elt',$params['end_time'] . ' 23:59:59');
        }   
        if($params['start_time'] && $params['end_time']){
            $map['cl.create_time'] = array(
                array('egt',$params['start_time'] . ' 00:00:00'),
                array('elt',$params['end_time'] . ' 23:59:59')
            );
        }
        $map['cl.type'] = array('eq',1);
        $cols = "cl.id,cl.aid,cl.commission_type,cl.amount,cl.create_time,a.uid,
                 c.car_id,c.series_id,c.car_no,c.car_cc,c.turbo,c.gearbox";
        $order = "cl.id DESC";
        $prefix = C('DB_PREFIX');
        $total = M('commission_log')->alias("cl")
                ->join($prefix. 'agent as a ON cl.aid=a.aid')
                ->join('LEFT JOIN ' . $prefix . 'cars AS c ON cl.car_id=c.car_id')
                ->where($map)->count();
        $commission_total  = M('commission_log')->alias("cl")
                ->field('SUM(amount) as commission_total')
                ->join($prefix. 'agent as a ON cl.aid=a.aid')
                ->where($map)->find();
        $list = M('commission_log')->alias("cl")->field($cols)
                ->join($prefix. 'agent as a ON cl.aid=a.aid')
                ->join('LEFT JOIN ' . $prefix . 'cars AS c ON cl.car_id=c.car_id')
                ->where($map)
                ->order($order)
                ->page($page)
                ->limit($page_size)
                ->select();
//        echo M()->getLastSql();
        $cm = new \AuctionCore\CarResource\CarModel();
        foreach($list as $k=>$v){
            $uid = Broker::getDetailByAid($v['aid']);
            $user = new \AuctionCore\Account\FrontUser();
            $info = $user->get_user_info_by_uid($uid['uid']);
            $list[$k]['agent_user'] =  $info['pwd_mobile'];
            if(!empty($v['car_id'])){
                $series = $cm->get_model_by_id($v['series_id'], 'series');
                $list[$k]['car_model_show'] = $series['name']. ' ' . $v['car_cc'] . ($v['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $v['gearbox']);;
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total,
            'commsission_total'=> sprintf("%01.2f",$commission_total['commission_total'])
        );
        return $result;
    }
	
    /**
     * @param $id
     * @param $data
     * @return bool
     */
    public static function updateLog($id,$data)
    {
        if($id<1 || empty($data)){
            return false;
        }
        return M('commission_log')->where("id={$id}")->save($data);
    }
}